package cn.knet.sp.ncrm.modules.sys.security.cas;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import cn.knet.sp.ncrm.common.security.shiro.session.SessionDAO;
import cn.knet.sp.ncrm.modules.sys.utils.web.util.WebUtils;


/**
 * @INFO:
 * @Author: Feng Yapeng
 * @Time: 2015/5/13 12:24
 */
public class SystemCasFilter extends CasFilter {

	private static Logger logger = LoggerFactory.getLogger(CasFilter.class);

	// the url where the application is redirected if the CAS service ticket validation failed (example : /mycontextpatch/cas_error.jsp)
	private String failureUrl;

	@Resource
	private SessionDAO sessionDAO;

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
									 ServletResponse response) throws Exception {
		Session session = subject.getSession();
		session= sessionDAO.readSession(session.getId());
		session.setAttribute("ticket", String.valueOf(token.getCredentials()));
		sessionDAO.update(session);
		issueSuccessRedirect(request, response);

		return false;
	}


	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request,
									 ServletResponse response) {
		// is user authenticated or in remember me mode ?
		Subject subject = getSubject(request, response);
		if (subject.isAuthenticated() || subject.isRemembered()) {
			try {
				issueSuccessRedirect(request, response);
			} catch (Exception e) {
				logger.error("Cannot redirect to the default success url", e);
			}
		} else {
			try {
				WebUtils.issueRedirect(request, response, this.failureUrl,
									   request.getParameterMap());
			} catch (IOException e) {
				logger.error("Cannot redirect to failure url : {}", failureUrl, e);
			}
		}
		return false;
	}

	public String getFailureUrl() {
		return failureUrl;
	}

	@Override
	public void setFailureUrl(String failureUrl) {
		this.failureUrl = failureUrl;
	}
}
